package com.test.uiapp2.tools;


import android.app.Instrumentation;
import android.content.Context;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.util.Log;

import androidx.annotation.Nullable;
import androidx.test.platform.app.InstrumentationRegistry;
import androidx.test.uiautomator.UiDevice;

import junit.framework.Assert;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by pc-zzw on 2017/12/4.
 * 权限处理 SDK >= M
 * pm list permissions : All Permissions
 * pm list permission-groups : All Permission Groups
 */

public class Permissions {
    private static Instrumentation instrument= InstrumentationRegistry.getInstrumentation();
    private static UiDevice mDevice= UiDevice.getInstance(instrument);

    /**
     * grant 命令处理当前程序(module app)的权限
     * @param permission such as : android.permission.WRITE_EXTERNAL_STORAGE
     * @throws IOException IO
     */
    public static void grantCurrentPermission(String permission) throws IOException {
        grantPermission(instrument.getTargetContext().getPackageName(),permission);
    }

    /**
     * grant 命令处理当前程序(module app)的所有权限
     * @throws IOException IO
     */
    public static void grantCurrentAllPermissions() throws IOException {
        grantAllPermissions(instrument.getTargetContext().getPackageName());
    }

    /**
     * grant 命令处理应用的权限
     * @param packageName such as : com.zzw.testdome
     * @param permission such as : android.permission.WRITE_EXTERNAL_STORAGE
     * @throws IOException IO
     */
    public static void grantPermission(String packageName , String permission) throws IOException {
        Assert.assertNotNull(packageName);
        Assert.assertNotNull(permission);
        Log.e("grantPermission: ",packageName+" "+permission);
        String cmd = String.format("pm grant %s %s",packageName , permission);
        String result = mDevice.executeShellCommand(cmd);
        Assert.assertTrue(result == null || !result.contains("Err"));
    }

    /**
     * 使用命令处理应用的所有权限
     * @param packageName Application Package Name
     */
    public static void grantAllPermissions(String packageName) throws IOException {
        Context context=instrument.getTargetContext();
        PackageInfo packageInfo = getPackageInfo(context, packageName);
        String[] permissions ;
        if (packageInfo != null) {
            permissions = packageInfo.requestedPermissions;
            permissions = extractUnGranted(context, packageName, permissions);
            if(permissions == null) return;
            for (String p : permissions) {
                Log.i("grantAllPermissions: ",packageName+"----"+p);
                grantPermission(packageName, p);
            }
        }
    }

    //提取未授权的权限
    private static String [] extractUnGranted(Context context,String packageName,String[] declaredPerms){
        if (declaredPerms == null || declaredPerms.length == 0) return null;
        PackageManager packageManager = context.getPackageManager();
        List<String> requestList = new ArrayList<>(declaredPerms.length);
        for (String permName : declaredPerms) {
            // 检查权限是否已授权
            int code = packageManager.checkPermission(permName, packageName);
            if (code == PackageManager.PERMISSION_GRANTED) continue;
            requestList.add(permName);
        }
        String[] unGranted = new String[requestList.size()];
        for (int i = 0; i < requestList.size(); i++) {
            unGranted[i] = requestList.get(i);
        }
        return unGranted;
    }

    //获取包的权限信息
    @Nullable
    private static PackageInfo getPackageInfo(Context context, String packageName){
        PackageManager packageManager = context.getPackageManager();
        try {
            return packageManager.getPackageInfo(packageName, PackageManager.GET_PERMISSIONS);
        } catch (PackageManager.NameNotFoundException e) {
            return null;
        }
    }
}
